package com.hanhai.common.util;

import javax.annotation.PostConstruct;

import org.apache.commons.lang3.ArrayUtils;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

/** 
 * 用户文件上传验证类 
 *  
 * @author Jacky Lau created at 2008-8-27 
 * @since 1.0 
 * @version 1.0 
 */  
public class MultipartFileValidator {  
  
    private final static long MAX_SIZE = 1024 * 1024;  
  
    /** 
     * 文件大小上限 
     */  
    private long maxSize = MAX_SIZE;  
  
    /** 
     * 可接受的文件content-type 
     */  
    private String[] allowedContentTypes;  
  
    @PostConstruct  
    public void afterPropertiesSet() {  
        Assert.notEmpty(allowedContentTypes,  
                        "The content types allowed to be uploaded must contain one at least!");  
    }  
  
    /** 
     * 验证上传文件是否合法，如果不合法那么会抛出异常 
     *  
     * @param file 
     *            用户上传的文件封装类 
     * @throws Exception 
     */  
    public void validate(MultipartFile file) throws Exception {  
        Assert.notNull(file, "The multipart file is null!");  
        if (file.getSize() > maxSize)  
            throw new Exception("error.upload.outmaxlen The file uploaded is out of max file size!");  
        if (!ArrayUtils.contains(allowedContentTypes, file.getContentType()))  
            throw new Exception("error.upload.content.notsupported The content type  is not a valid content type !");  
    }  
  
    /** 
     * 设置文件上传大小上限 
     *  
     * @param maxSize 
     *            文件上传大小上限 
     */  
    public void setMaxSize(long maxSize) {  
        this.maxSize = maxSize;  
    }  
  
    /** 
     * 设置可接受的文件content-type数组 
     *  
     * @param allowedContentTypes 
     *            可接受的文件content-type数组 
     */  
    public void setAllowedContentTypes(String[] allowedContentTypes) {  
        this.allowedContentTypes = allowedContentTypes;  
    }  
  
}  